import {
  wxRequest
} from '../../utils/server.js';
const _wxRequest = new wxRequest();
let isSend = false;
let a5TryCount = 0;
const app = getApp()
let clockId = 0;
const bluetooth = require('../../utils/bluetooth');
const NewBluetooth = require('../../utils/newBluetooth');
let newBluetooth = new NewBluetooth();
import RgjBleHelper from '../../utils/ble/RgjBleHelper.js'
let commitId = 0;
let hasFindBlue = false;
// 轮询接口 查询提交状态
// 轮询次数
let requestCount = 3;
// 轮询持续时间(ms)
let requestTotalTime = 10000;
// 轮询定时器ID
let intervalId = 0;
// 轮询间隔
let intervalTime = requestTotalTime / requestCount;

// 蓝牙后
let onBlueStartRequest = {
  requestSend: false,
  requestCount: 3,
  requestTotalTime: 10000,
  requestIntervalId: 0,
  requestSendA6: false,
  deviceResponse: false,
  hasSend0080: false,
  hasSend00B0: false
}

onBlueStartRequest.requestIntervalTime = onBlueStartRequest.requestTotalTime / onBlueStartRequest.requestCount

Page({

  /**
   * 页面的初始数据
   */
  data: {
    device: {},
    typeIndex: "",
    deviceList: [],
    uploadUrl: wx.getStorageSync('uploadUrl'),
    weightList: [30, 60, 90, 120],
    selectWeightIndex: 0,
    formulaList: [],
    selectFormulaIndex: 0,
    bluetoothDeviceList: [],
    mac: '',
    btid: '',

    devId: '',

    maxWeight: '',
    minWeight: '',
    // 是否是mini机型
    isMini: wx.getStorageSync('isMini'),
    // 蓝牙实例
    rgjBleHelper: {}
  },
  bindPickerChange(e) {
    var val = e.detail.value
    this.setData({
      typeIndex: val
    })
  },

  onLoad: function (options) {
    // const eventChannel = this.getOpenerEventChannel()
    // eventChannel.on && eventChannel.on('colorItem', data => {
    //   this.setData({
    //     itemColor: data,
    //   })
    // })
  },

  onShow: function (options) {
    console.log('options', options)
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面   
    console.log(prevPage.data.itemColor, 'prevPage.itemColor')
    let itemColor = prevPage.data.itemColor;
    if (itemColor.operationJson) {
      itemColor.operationJson = itemColor.operationJson.replace(/\n/g, "<br/>")
    } else {
      itemColor.operationJson = ""
    }
    // itemColor.operationJson = itemColor.operationJson ?itemColor.operationJson.replaceAll("\n", "<br/>"):""

    //如果是定制配方类型设备
    let formulaRatioJson = []
    prevPage.data.itemColor.formulaRatioJson && (formulaRatioJson = JSON.parse(prevPage.data.itemColor.formulaRatioJson))

    this.setData({
      itemColor: prevPage.data.itemColor,
      formulaRatioJson
    }, () => {
      this.getDeviceList();
      this.getColorFindList();
      if (formulaRatioJson.length > 0) this.getDeviceTypeVo()
    })

  },

  initRgjBleHelper() {
    this.data.rgjBleHelper = new RgjBleHelper({
      mac: this.data.deviceList[this.data.typeIndex].code,
      statusChangeCallback: async (status) => {
        console.log(status)
        wx.hideLoading()
        this.resetBlueRequest();
        this.resetRequest();
        if (status == RgjBleHelper.BLUE_DYE_COLOR_TIMEOUT) {
          wx.showToast({
            title: '下料超时!',
            icon: 'none'
          })
          await this.updateDyeRecord(false, '超时')
          this.data.rgjBleHelper.initBLEStatus()
        }
        if (status == RgjBleHelper.BLUE_DYE_COLOR_FINISH) {
          wx.showToast({
            title: '下料成功！',
            icon: 'none'
          })
          await this.updateDyeRecord(true, '成功')
          this.data.rgjBleHelper.initBLEStatus()
          wx.redirectTo({
            url: '/pages/color_recode/index',
          })
        }
        if (status == RgjBleHelper.BLUE_DYE_COLOR_FAILED) {
          wx.showToast({
            title: '下料失败，请重试！',
            icon: 'none'
          })
          await this.updateDyeRecord(false, '失败')
          this.data.rgjBleHelper.initBLEStatus()
        }
        if (status == RgjBleHelper.BLUE_SERVICE_FAILED || status == RgjBleHelper.BLUE_STATUS_FAILED) {
          wx.hideLoading()
          await this.updateDyeRecord(false, '失败')
          this.data.rgjBleHelper.initBLEStatus()
        }
      }
    })
    this.data.rgjBleHelper.initBlue(this.data.deviceList[this.data.typeIndex].code)
  },

  async updateDyeRecord(isSucceed, message) {
    return new Promise((resolve, reject) => {
      let params = {
        mac: this.data.mac,
        commitId: this.data.commitId,
        status: isSucceed ? 1 : 0,
        message
      }
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/gds/protected/dyeRecord/updateDyeRecord',
        data: params,
        method: 'POST',
      }, (res) => {
        resolve(true)
      })
    })
  },

  onHide: function () {
    this.data.rgjBleHelper.initBLEStatus()
    this.resetBlueRequest();
    this.resetRequest();
    this.closeBlueFea();
    hasFindBlue = false;
  },

  onUnload: function () {
    this.data.rgjBleHelper.initBLEStatus()
    this.resetBlueRequest();
    this.resetRequest();
    this.closeBlueFea();
    hasFindBlue = false
    // 不能清除设备id，第二次进入查询设备列表为[]  张循  2022 4 4
    //wx.removeStorageSync('devicesTypeId') 
  },

  closeBlueFea() {
    newBluetooth.stopBluetoothScan();
    bluetooth.bluetooth.write_no();
    bluetooth.bluetooth.close_bt(this.data.btid, function (res) {
      console.log("关闭蓝牙成功：" + res);
    }, function (res) {
      console.log("关闭蓝牙错误：" + res);
    });
  },

  changeCurrentColor(e) {
    const targetColor = e.currentTarget.dataset.colorIndex
    this.setData({
      selectWeightIndex: targetColor
    })
  },

  //获取设备类型
  getDeviceTypeVo() {
    const itemColor = this.data.itemColor
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/comm/beanCrud/iot.DeviceTypeVO/getById/' + itemColor.typeId,
      method: 'GET',
    }, (res) => {
      const deviceTypeVO = res.vo
      let minWeight = ''
      let maxWeight = ''
      if (itemColor.maxWeight && itemColor.minWeight) {
        minWeight = itemColor.minWeight
        maxWeight = itemColor.maxWeight
      } else {
        minWeight = deviceTypeVO.minWeight
        maxWeight = deviceTypeVO.maxWeight
      }
      this.setData({
        minWeight,
        maxWeight
      })
    })
  },
  //查配方列表
  getColorFindList: function () {
    var params = {
      pid: this.data.itemColor.id
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeColor/findList',
      method: 'POST',
      data: params,
      loading: false
    }, (res) => {
      if (this.data.itemColor.id) {
        this.setData({
          formulaList: res.list
        })
      }
    })
  },

  changeCurrentColorFormula(e) {
    let targetColor = e.currentTarget.dataset.colorFormulaIndex
    // if(this.data.selectFormulaIndex == targetColor) {
    //   targetColor = -1;
    // }
    this.setData({
      selectFormulaIndex: targetColor
    })
  },

  //获取设备列表
  getDeviceList: function () {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/device/findList',
      method: 'POST',
      data: {
        keyword: this.data.keyword,
        pageNo: 1,
        pageSize: 100,
        typeId: wx.getStorageSync('devicesTypeId'),
        orgType: 3,
        noCountDye: 1
      }
    }, (res) => {
      let list = res.list;
      let devId = wx.getStorageSync('devId') || this.data.itemColor.devId
      this.data.typeIndex = list.findIndex(value => value.id === devId)
      console.log(this.data.typeIndex, 123123)
      this.setData({
        deviceList: list,
        typeIndex: this.data.typeIndex != -1 ? this.data.typeIndex : 0
      });

      wx.openBluetoothAdapter({
        success: (res) => {
          console.log(res, '蓝牙打开')
          setTimeout(() => {
            this.initRgjBleHelper()
          }, 600)
        },
        fail: err => {
          console.log(err, '蓝牙没打开')
        }
      })
    })
  },

  formSubmit: async function (e) {
    var formdata = e.detail.value;
    formdata.recType = 1
    if (this.data.typeIndex === '') {
      wx.showToast({
        icon: 'none',
        title: '请选择设备',
      })
      return
    }
    if (this.data.itemColor.modeVal == 2) {
      // 畅想模式 
      if (formdata.weight < 1) {
        wx.showToast({
          icon: 'none',
          title: '染膏剂量必须大于1g',
        })
        return
      }

      if (formdata.weight > 120) {
        wx.showToast({
          icon: 'none',
          title: '染膏剂量必须小于120g',
        })
        return
      }
    } else {
      if (this.data.itemColor.formulaCustomized != 1)
        formdata.weight = this.data.weightList[this.data.selectWeightIndex]
    }

    if (!this.data.deviceList[this.data.typeIndex].deviceName) {
      wx.showToast({
        icon: 'none',
        title: '请选择设备',
      })
      return
    }
    let tipsContent = `当前调色为：【${this.data.itemColor.colorName}】`;
    let isDioxygen = false //是否双氧
    formdata.devId = this.data.deviceList[this.data.typeIndex].id
    if (this.data.formulaList.length != 0) {
      if (this.data.selectFormulaIndex == -1) {
        wx.showToast({
          title: "请至少选择一个配方",
          icon: "none"
        })
        return;
      }
      const formula = this.data.formulaList[this.data.selectFormulaIndex]
      console.log(formula, 'formual')
      formdata.colorId = formula.id;
      tipsContent += `-【${formula.colorName}】`;
      if (formula.colorName.indexOf('双氧') != -1) {
        console.log('是双氧');
        isDioxygen = true
        //formdata.weight = formdata.weight * 2
      } else {
        isDioxygen = false
        console.log('不是双氧');
      }
    } else {
      formdata.colorId = this.data.itemColor.id;
    }
    let showWeight = formdata.weight; // 最终下料的克数
    if (this.data.itemColor.minWeight && this.data.itemColor.maxWeight && this.data.itemColor.formulaCustomized == 1) {
      if (formdata.weight > this.data.itemColor.maxWeight || formdata.weight < this.data.itemColor.minWeight) {
        wx.showToast({
          icon: 'none',
          title: '染膏剂量必须在' + this.data.itemColor.minWeight + "-" + this.data.itemColor.maxWeight + "克之间",
        })
        return
      }
      isDioxygen && (showWeight = formdata.weight * 2)
    }
    console.log(formdata);
    console.log(tipsContent);
    console.log(showWeight);
    tipsContent += `总量为：${showWeight}克，是否确定调色？`;
    let selectDeviceItem = this.data.deviceList[this.data.typeIndex];
    wx.showModal({
      content: tipsContent,
      success: (async res => {
        if (res.confirm) {
          this.formRequest(formdata)
        }
      })
    })

  },

  //请求
  formRequest: function (formdata) {
    var url = '/gds/protected/dyeRecord/create';
    var title = "操作成功"
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, async (res) => {
      // wx.showLoading({
      // 	title: '等待结果中',
      // })
      console.log(res, 111)
      commitId = res.data.commitId;
      wx.showLoading({
        title: '查询结果中...',
      })

      intervalId = setInterval(() => {
        // 轮询请求
        _wxRequest.wxTonkenAjax({
          loading: false,
          url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getByCommitId?devId=' + that.data.deviceList[that.data.typeIndex].id + '&commitId=' + commitId,
          method: 'GET'
        }, async (res1) => {
          console.log(res1, 222)
          let dyeRecord = res1.vo;
          let isSuccess = false;
          if (dyeRecord == null) {
            isSuccess = false;
          } else {
            isSuccess = dyeRecord.status == 21 || dyeRecord.status == 0 || dyeRecord.status == 13;
          }


          if (requestCount < 1 && !isSuccess) {
            // 轮询结束 还没跳转 用蓝牙补发
            // 后台自动判断是否下发
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '设备当前信号弱，将使用线下模式，请打开蓝牙并且确保距离设备1米以内',
              success: async (confirmRes) => {

                if (confirmRes.confirm) {
                  wx.showLoading({
                    title: '正在连接设备',
                  })

                  if (this.data.isMini) {
                    await this.scanCodeClick();
                    this.findBlue(res.data.hex);
                  } else {
                    // 新板蓝牙
                    let mac = this.data.deviceList[this.data.typeIndex].code
                    let colorNo = this.data.itemColor.code
                    let useAmount = formdata.weight
                    let commitId = res1.vo.commitId
                    let formulaNumJson = JSON.parse(res1.vo.formulaNumJson)
                    let cList = []
                    formulaNumJson.forEach((item) => {
                      let params = {
                        [item.cnum]: item.value
                      }
                      cList.push(params)
                    })
                    this.setData({
                      mac,
                      commitId
                    })
                    this.data.rgjBleHelper.startDyeColor(mac, colorNo, useAmount, commitId, cList)
                  }
                }
              }
            })
            this.resetRequest();
          } else {
            if (isSuccess) {
              if (dyeRecord.status == 0) {
                wx.showToast({
                  duration: 3000,
                  icon: 'none',
                  title: dyeRecord.note,
                })
              }
              //wx.hideLoading();
              // 调色已由物联网发送完成 直接跳转到调色记录即可
              wx.redirectTo({
                url: '/pages/color_recode/index',
              })
              clearInterval(intervalId);
            }
          }
          requestCount--;
        })

      }, intervalTime);
    })
  },

  resetRequest() {
    clearInterval(intervalId);
    // 轮询接口 查询提交状态
    // 轮询次数
    requestCount = 3;
    // 轮询持续时间(ms)
    requestTotalTime = 6000;
    // 轮询定时器ID
    intervalId = 0;
    // 轮询间隔
    intervalTime = requestTotalTime / requestCount;
  },

  resetBlueRequest() {
    clearInterval(onBlueStartRequest.requestIntervalId);
    onBlueStartRequest = {
      requestSend: false,
      requestCount: 3,
      requestTotalTime: 10000,
      requestIntervalId: 0,
      requestSendA6: false,
      deviceResponse: false,
      hasSend0080: false,
      hasSend00B0: false
    }

    onBlueStartRequest.requestIntervalTime = onBlueStartRequest.requestTotalTime / onBlueStartRequest.requestCount
  },

  scanCodeClick: function (e) {
    var that = this;
    return new Promise(async (resolve, reject) => {
      // 初始化蓝牙
      try {
        //等待蓝牙状态返回
        await newBluetooth.initScanBluetoothDevice();
        newBluetooth.startScanDevice();
        let foundedDevice = await newBluetooth.getBlueDevice();
        let bluetoothDeviceList = that.data.bluetoothDeviceList;
        bluetoothDeviceList = bluetoothDeviceList.concat(foundedDevice.devices);
        that.setData({
          bluetoothDeviceList
        });
        //没有蓝牙地址  查找蓝牙列表中 是否有名称为mac的设备
        newBluetooth.listenOnDeviceFounded(res => {
          let bluetoothDeviceList = that.data.bluetoothDeviceList;
          bluetoothDeviceList = bluetoothDeviceList.concat(res.devices);
          that.setData({
            bluetoothDeviceList
          });
          let findDevice = bluetoothDeviceList.filter(item => item.name == that.data.deviceList[that.data.typeIndex].code);
          if (findDevice.length > 0) {
            that.setData({
              btid: findDevice[0].deviceId
            })
            resolve();

          }
        });
      } catch (e) {

        console.log(e);
        if (e.errCode == 10001) {
          wx.showToast({
            icon: 'none',
            title: '请打开蓝牙'
          })
        }
        reject();
      }
    })
  },

  findBlue(str) {
    var that = this;
    //链接蓝牙
    console.log("开始连接蓝牙", this.data.deviceList[this.data.typeIndex].code, this.data.btid);
    bluetooth.bluetooth.openBlue(this.data.deviceList[this.data.typeIndex].code, this.data.btid,
      function (_res) {
        that.setData({
          conn_msg: _res
        });
        //bluetooth.bluetooth.set_down_hex(str);

        //bluetooth.bluetooth.write_value(str);
      },
      function (_res) {
        // 写入成功回调

        // 如果写入00b0
        console.log('写入数据00b0：', _res.toLowerCase(), onBlueStartRequest.hasSend00B0);
        if (_res.toLowerCase().indexOf('660000b0') == 0 && !onBlueStartRequest.hasSend00B0) {
          // 标记为已发送00B0
          onBlueStartRequest.hasSend00B0 = true;

          setTimeout(() => {
            // 如果2s之后设备没回复00B0， 则开始服务器轮询
            if (!onBlueStartRequest.requestSend) {
              // 如果写入没有发起轮询 则发起轮询
              wx.showLoading({
                title: '查询结果中...',
              })
              onBlueStartRequest.requestIntervalId = setInterval(() => {
                // 轮询请求
                _wxRequest.wxTonkenAjax({
                  loading: false,
                  url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getByCommitId?devId=' + that.data.deviceList[that.data.typeIndex].id + '&commitId=' + commitId,
                  method: 'GET'
                }, async (res1) => {
                  let dyeRecord = res1.vo;
                  let isSuccess = false;
                  if (dyeRecord == null) {
                    isSuccess = false;
                  } else {
                    isSuccess = dyeRecord.status == 21 || dyeRecord.status == 0 || dyeRecord.status == 13;
                  }
                  if (onBlueStartRequest.requestCount <= 0 && !isSuccess) {
                    //wx.hideLoading();
                    // 后台自动判断是否下发
                    wx.showModal({
                      title: '提示',
                      content: '本次下料未有结果',
                      showCancel: false,
                      success: async (confirmRes) => {
                        if (confirmRes.confirm) {
                          wx.redirectTo({
                            url: '/pages/color_recode/index',
                          })

                          that.closeBlueFea();
                        }
                      }
                    })
                    that.resetBlueRequest();
                  } else {
                    if (res1.vo) {
                      // wx.showLoading({
                      // 	title: '查询结果中...',
                      // })
                      // 如果不是等待中 说明已有结果
                      if (isSuccess) {

                        if (dyeRecord.status == 0) {
                          wx.hideLoading();
                          // 状态异常弹窗提示
                          wx.showToast({
                            duration: 3000,
                            icon: 'none',
                            title: dyeRecord.note,
                          })
                          // that.closeBlueFea();
                          // console.log('关闭的定时器ID', onBlueStartRequest.requestIntervalId)
                          // // 结束轮询
                          // clearInterval(onBlueStartRequest.requestIntervalId);
                          // // 
                          // that.resetRequest();
                          // that.resetBlueRequest();
                        }

                        wx.hideLoading();
                        console.log('后台已有结果，当前A6发送状态', onBlueStartRequest.requestSendA6);
                        // 后台已有回调结果 发送A6给设备获取0080指令
                        onBlueStartRequest.requestSendA6 = true;
                        bluetooth.bluetooth.write_value("A6");
                        // 结束轮询
                        clearInterval(onBlueStartRequest.requestIntervalId);
                      }
                    }
                  }
                  onBlueStartRequest.requestCount--;
                })
              }, onBlueStartRequest.requestIntervalTime);
              console.log('开启定时器', onBlueStartRequest.requestIntervalId);
              // 修改为已发起
              onBlueStartRequest.requestSend = true;
            }
          }, 5000);
        }

        if (_res.toLowerCase().indexOf('66000080') == 0 && !onBlueStartRequest.hasSend0080) {
          // 标记为已发送0080
          console.log('写入数据0080：', _res);
          onBlueStartRequest.hasSend0080 = true;
          setTimeout(() => {
            wx.showToast({
              title: '染色成功',
              success: () => {
                setTimeout(() => {
                  that.resetBlueRequest();
                  wx.redirectTo({
                    url: '/pages/color_recode/index',
                  })
                  that.resetRequest();
                  that.closeBlueFea();
                }, 1000);
              }
            })

          }, 1000);
        }


      },
      function (_res) {
        console.log('收到数据：', _res);
        if (_res.toLowerCase().indexOf("660000b0") == 0) {
          onBlueStartRequest.deviceResponse = true;
          console.log('收到设备的00B0，下传A6采集数据')
          setTimeout(() => {
            console.log('后台无结果2s后无结果，当前A6状态', onBlueStartRequest.requestSendA6);
            if (!onBlueStartRequest.requestSendA6) {
              bluetooth.bluetooth.write_value("A6");
              onBlueStartRequest.requestSendA6 = true;
            }
          }, 5000)
        }

        if (_res.toLowerCase().indexOf('66000080') == 0) {
          // 检测到下料已经成功  关闭蓝牙
          // bluetooth.bluetooth.write_no();
          // bluetooth.bluetooth.close_bt(that.data.btid, function(res) {
          //   console.log("关闭蓝牙成功：" + res);
          // }, function(res) {
          //   console.log("关闭蓝牙错误：" + res);
          // });
          if (onBlueStartRequest.requestSendA6) {
            if (onBlueStartRequest.hasSend0080) {
              wx.showToast({
                title: '染色成功',
              })
              that.resetBlueRequest();
              wx.redirectTo({
                url: '/pages/color_recode/index',
              })
            }

          }

        }
      },
      function (res2) {
        console.log('广播通知绑定成功')
        if (!hasFindBlue) {
          bluetooth.bluetooth.write_value(str);
          hasFindBlue = true
        }

      }
    );
  }

})